package org.example.chat.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 系统线程池配置
 * @author cheval
 */
@EnableAsync
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int coreCount = Runtime.getRuntime().availableProcessors();
        // 1. 配置核心线程池大小， io多的情况，设置多一点（2倍cpu核心）。 其他设置为cpu核心个数
        executor.setCorePoolSize(coreCount);
        // 2. 配置最大线程池大小
        executor.setMaxPoolSize(2 * coreCount);
        // 3. 配置阻塞队列大小、
        executor.setQueueCapacity(coreCount);
        // 4. 配置核心线程永不过期
        executor.setAllowCoreThreadTimeOut(false);
        // 5. 配置线程空闲超时释放时间
        executor.setKeepAliveSeconds(60);
        // 6. 配置拒接策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 7. 设置线程前缀名
        executor.setThreadNamePrefix("Task-");
        return executor;
    }
}
